# -*- coding: utf-8 -*-
###############################################################################
# file    : my_decorator.py
# author  : wangyubin
# date    : 2013-09-14
# 
# brief   : decorators for apps
# history : init
###############################################################################

import traceback

from my_log import App_Log


def wraps(src):
    """
    active decorator in views
    reference: uliweb/utils/common.py(def wraps)
    """
    def _f(des):
        def f(*args, **kwargs):
            from uliweb import application
            if application:
                env = application.get_view_env()
                for k, v in env.iteritems():
                    src.func_globals[k] = v
                
                src.func_globals['env'] = env
            return des(*args, **kwargs)
        
        f.__name__ = src.__name__
        f.func_globals.update(src.func_globals)
        f.__doc__ = src.__doc__
        f.__module__ = src.__module__
        f.__dict__.update(src.__dict__)
        return f
    
    return _f


def loginfo_start_end(func):
    """
    在函数进入和退出时打印log
    """
    @wraps(func)
    def d(*args, **kwords):
        App_Log.logger.info("[ENTRY] function: " + func.func_name)
        result = func(*args, **kwords)
        App_Log.logger.info("[EXIT]  function: " + func.func_name)
        return result

    return d
        


def catch_except(func):
    """
    捕获函数执行过程中的异常
    """
    @wraps(func)
    def d(*args, **kwords):
        try:
            return func(*args, **kwords)
        except Exception, ex:
            App_Log.logger.critical("[Critical Message]: " + ex.message)
            App_Log.logger.critical("[Critical detail] : \n" + traceback.format_exc())
            return error(traceback.format_exc())
            
    return d
        
